/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Presentacion;

import ManejoExc.ClienteException;
import Negocio.Cliente;
import Negocio.Empresa;
import Utils.Crypt;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Map;
import javax.swing.DefaultListModel;
import javax.swing.JOptionPane;

/**
 *
 * @author Diego
 */
public class FrmCliente extends javax.swing.JDialog {
    Empresa unaEmpresa;
    Cliente unCliente;
    Crypt miClaseEncryptacion = new Crypt();
    DefaultListModel modelClientes = new DefaultListModel();
    

    /**
     * Creates new form FrmCliente
     */
    public FrmCliente(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
    }
    
    public FrmCliente(java.awt.Frame parent, boolean modal,Empresa unaEmpresa) {
        super(parent, modal);
        initComponents();
        this.unaEmpresa = unaEmpresa;
        this.inicializar();
        
        //this.inicializar();
        
    }
    
    /*
     * Mis Metodos
     */
    
    public void inicializar() {
        this.LstClientes.setModel(modelClientes);
        this.cargarClientes();
        this.setTitle("Clientes");
        this.unCliente=null;
        
        this.TxtRazonSocial.setEnabled(false);
        this.TxtCuit.setEnabled(false);
        this.TxtDireccion.setEnabled(false);
        this.TxtTelefono.setEnabled(false);
        this.TxtPassword.setEnabled(false);
        this.TxtPassword2.setEnabled(false);
        
        this.TxtRazonSocial.setText("");
        this.TxtCuit.setText("");
        this.TxtDireccion.setText("");
        this.TxtTelefono.setText("");
        this.TxtPassword.setText("");
        this.TxtPassword2.setText("");
        this.TxtEmail.setText("");
        
        this.BtnSave.setEnabled(false);
        this.BtnDelete.setEnabled(false);
        this.BtnCancel.setEnabled(false);
        this.BtnNuevo.setEnabled(true);
    }
    
    public void ponerEnBlanco(){        
        this.TxtRazonSocial.setEnabled(true);
        this.TxtCuit.setEnabled(true);
        this.TxtDireccion.setEnabled(true);
        this.TxtTelefono.setEnabled(true);
        this.TxtPassword.setEnabled(true);
        this.TxtPassword2.setEnabled(true);
        this.TxtEmail.setEnabled(true);
        this.TxtRazonSocial.setText("");
        this.TxtCuit.setText("");
        this.TxtDireccion.setText("");
        this.TxtTelefono.setText("");
        this.TxtPassword.setText("");
        this.TxtPassword2.setText("");
        this.TxtEmail.setText("");
        
        this.BtnSave.setEnabled(true);
        this.BtnDelete.setEnabled(true);
        this.BtnCancel.setEnabled(true);
        this.BtnNuevo.setEnabled(false);
    }
    
    public void cargarClientes(){
        this.modelClientes.clear();        
        if(this.unaEmpresa.getClientes()!= null && this.unaEmpresa.getClientes().size() > 0){
            for (Map.Entry cliente : this.unaEmpresa.getClientes().entrySet()) {
                this.modelClientes.addElement((Cliente) cliente.getValue());
            }
        }else{
            this.modelClientes.addElement("No se Encontraron Clientes");
        } 
        
    }
    public void completarCampos(){
        this.ponerEnBlanco();
        this.TxtCuit.setText(this.unCliente.getCuit());
        this.TxtDireccion.setText(this.unCliente.getDireccion());
        this.TxtEmail.setText(this.unCliente.getEmail());
        this.TxtRazonSocial.setText(this.unCliente.getRazonSocial());
        this.TxtTelefono.setText(this.unCliente.getTelefono());
        this.TxtPassword.setText(this.unCliente.getPassword());
        this.TxtPassword2.setText(this.unCliente.getPassword());

    }
    
    
    
    
    /*
     * Fin Mis Metodos
     */

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        LstClientes = new javax.swing.JList();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        TxtRazonSocial = new javax.swing.JTextField();
        TxtDireccion = new javax.swing.JTextField();
        TxtTelefono = new javax.swing.JTextField();
        jLabel8 = new javax.swing.JLabel();
        TxtEmail = new javax.swing.JTextField();
        BtnSave = new javax.swing.JButton();
        BtnCancel = new javax.swing.JButton();
        BtnDelete = new javax.swing.JButton();
        TxtPassword = new javax.swing.JPasswordField();
        TxtPassword2 = new javax.swing.JPasswordField();
        BtnNuevo = new javax.swing.JButton();
        BtnOk = new javax.swing.JButton();
        jLabel5 = new javax.swing.JLabel();
        TxtCuit = new javax.swing.JFormattedTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        LstClientes.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        LstClientes.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                LstClientesMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(LstClientes);

        jLabel1.setText("Razon Social");

        jLabel2.setText("Cuit");

        jLabel3.setText("Direccion");

        jLabel4.setText("Telefono");

        jLabel6.setText("Password");

        jLabel7.setText("Re-Password");

        TxtRazonSocial.setEnabled(false);

        TxtDireccion.setEnabled(false);

        TxtTelefono.setEnabled(false);

        jLabel8.setText("E-Mail");

        TxtEmail.setEnabled(false);

        BtnSave.setText("Guardar");
        BtnSave.setEnabled(false);
        BtnSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BtnSaveActionPerformed(evt);
            }
        });

        BtnCancel.setText("Cancelar");
        BtnCancel.setEnabled(false);
        BtnCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BtnCancelActionPerformed(evt);
            }
        });

        BtnDelete.setText("Borrar");
        BtnDelete.setEnabled(false);
        BtnDelete.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BtnDeleteActionPerformed(evt);
            }
        });

        TxtPassword.setEnabled(false);

        TxtPassword2.setEnabled(false);

        BtnNuevo.setText("Nuevo");
        BtnNuevo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BtnNuevoActionPerformed(evt);
            }
        });

        BtnOk.setText("Aceptar");
        BtnOk.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BtnOkActionPerformed(evt);
            }
        });

        jLabel5.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabel5.setText("Clientes");

        try {
            TxtCuit.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##-########-#")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        TxtCuit.setEnabled(false);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 228, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 111, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel1)
                            .addComponent(jLabel2)
                            .addComponent(jLabel3)
                            .addComponent(jLabel4))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(TxtTelefono)
                            .addComponent(TxtDireccion)
                            .addComponent(TxtRazonSocial)
                            .addComponent(TxtCuit)))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel7)
                            .addComponent(jLabel6)
                            .addComponent(jLabel8))
                        .addGap(15, 15, 15)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(TxtPassword, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(TxtPassword2, javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(TxtEmail)))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 50, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addComponent(BtnNuevo)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(BtnSave)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(BtnDelete)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(BtnCancel))
                            .addComponent(BtnOk, javax.swing.GroupLayout.Alignment.TRAILING))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(TxtRazonSocial, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel2)
                            .addComponent(TxtCuit, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel3)
                            .addComponent(TxtDireccion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel4)
                            .addComponent(TxtTelefono, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel6)
                            .addComponent(TxtPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel7)
                            .addComponent(TxtPassword2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel8)
                            .addComponent(TxtEmail, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(BtnCancel)
                            .addComponent(BtnDelete)
                            .addComponent(BtnSave)
                            .addComponent(BtnNuevo))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(BtnOk)
                        .addContainerGap())
                    .addGroup(layout.createSequentialGroup()
                        .addGap(3, 3, 3)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 477, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap(24, Short.MAX_VALUE))))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void BtnCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtnCancelActionPerformed
        // TODO add your handling code here:
        this.ponerEnBlanco();
        this.cargarClientes();
        this.unCliente = null;
    }//GEN-LAST:event_BtnCancelActionPerformed

    private void LstClientesMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_LstClientesMouseClicked
        // TODO add your handling code here:
        this.unCliente = (Cliente) this.modelClientes.getElementAt(this.LstClientes.getSelectedIndex());
        this.completarCampos();
    }//GEN-LAST:event_LstClientesMouseClicked

    private void BtnSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtnSaveActionPerformed
        // TODO add your handling code here:
        String pass;
        String pass1, pass2;
        pass1 = new String(this.TxtPassword.getPassword()); 
        pass2 = new String( this.TxtPassword2.getPassword());
        if(this.unCliente!= null){
            //this.unCliente.actualizarDatos();

             if(pass1.equals(pass2)){ //si los pass son iguales
                 //pass = new String(this.TxtPassword.getPassword());
                 
                 try{
                     
                     //si cambio pass pregunto para actualizar
                     //si quiere actualizar llamo a este 
                     //si 0
                     //no 1
                     //cancel 2                     
                     
                     int mc,bc,ch=1;
                     if(this.unCliente.cambioPassword(pass1)){
                         mc = JOptionPane.QUESTION_MESSAGE;
                         bc = JOptionPane.YES_NO_CANCEL_OPTION;
                         ch = JOptionPane.showConfirmDialog (this, "Los datos del LogIn han Cambiado. Desea Actualizar?", "LogIn Confirmacion", bc, mc);    
                     }
                     
                     if(ch == 0){
                        pass = new String(this.TxtPassword.getPassword());
                        this.unaEmpresa.actualizarDatosCliente(this.unCliente,this.TxtRazonSocial.getText(),this.TxtCuit.getText(),this.TxtDireccion.getText(),this.TxtTelefono.getText(),Empresa.miClaseEncriptadora.encriptar(pass),this.TxtEmail.getText());
                     }else if(ch == 1){
                         //sino llamo a est otro
                         System.out.println(this.TxtCuit.getText());
                       this.unaEmpresa.actualizarDatosCliente(this.unCliente,this.TxtRazonSocial.getText(),this.TxtCuit.getText(),this.TxtDireccion.getText(),this.TxtTelefono.getText(),this.TxtEmail.getText());
                     }
                    
                    this.inicializar();   
                 }
                 catch (ClienteException ex){
                     JOptionPane.showMessageDialog(this, ex.getMessage());
                 }
                 catch (NoSuchAlgorithmException ex){
                     JOptionPane.showMessageDialog(this, ex.getMessage());
                 }
                 catch (Exception ex){
                     JOptionPane.showMessageDialog(this, ex.getMessage());
                 }
             }else{
                 JOptionPane.showMessageDialog(this, "Las Contraseñas ingresadas no son iguales");
             }
        }else{
            
            if(pass1.equals(pass2)){
                try{
                    this.unaEmpresa.nuevoCliente(this.TxtRazonSocial.getText(),this.TxtCuit.getText(),this.TxtDireccion.getText(),this.TxtTelefono.getText(),this.miClaseEncryptacion.encriptar(pass1),this.TxtEmail.getText());
                    this.inicializar();
                }
                catch(NoSuchAlgorithmException ex){
                     JOptionPane.showMessageDialog(this, ex.getMessage());
                }
                catch(Exception ex){
                     JOptionPane.showMessageDialog(this, ex.getMessage());
                }
            }else{
                JOptionPane.showMessageDialog(this, "Las Contraseñas ingresadas no son iguales");
            }
        }
    }//GEN-LAST:event_BtnSaveActionPerformed

    private void BtnOkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtnOkActionPerformed
        // TODO add your handling code here:
        this.setVisible(false);
    }//GEN-LAST:event_BtnOkActionPerformed

    private void BtnNuevoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtnNuevoActionPerformed
        // TODO add your handling code here:
        this.ponerEnBlanco();
        this.unCliente = null;

    }//GEN-LAST:event_BtnNuevoActionPerformed

    private void BtnDeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BtnDeleteActionPerformed
        // TODO add your handling code here:
        int mc,bc,ch=1;
        mc = JOptionPane.QUESTION_MESSAGE;
        bc = JOptionPane.YES_NO_CANCEL_OPTION;
        ch = JOptionPane.showConfirmDialog (this, "Desea borrar al cliente seleccinado?", "Confirmacion", bc, mc); 
        if(ch == 0){
            this.unCliente.darDeBaja();
            JOptionPane.showMessageDialog(this, "La operacion se realizo correctamente");
            this.ponerEnBlanco();
            this.cargarClientes();
        }
    }//GEN-LAST:event_BtnDeleteActionPerformed

    /**
     * @param args the command line arguments
     */

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton BtnCancel;
    private javax.swing.JButton BtnDelete;
    private javax.swing.JButton BtnNuevo;
    private javax.swing.JButton BtnOk;
    private javax.swing.JButton BtnSave;
    private javax.swing.JList LstClientes;
    private javax.swing.JFormattedTextField TxtCuit;
    private javax.swing.JTextField TxtDireccion;
    private javax.swing.JTextField TxtEmail;
    private javax.swing.JPasswordField TxtPassword;
    private javax.swing.JPasswordField TxtPassword2;
    private javax.swing.JTextField TxtRazonSocial;
    private javax.swing.JTextField TxtTelefono;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JScrollPane jScrollPane1;
    // End of variables declaration//GEN-END:variables
}
